package com.sunb2b.web.controller;

import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sunb2b.entity.CompanyMember;
import com.sunb2b.entity.Member;
import com.sunb2b.entity.PersonMember;
import com.sunb2b.entity.Region;
import com.sunb2b.pojo.PageSearchResult;
import com.sunb2b.service.MemberService;
import com.sunb2b.service.RegionService;
import com.sunb2b.util.WebUtils;
import com.sunb2b.web.form.MemberSearchForm;

@Controller
public class MemberController {
    
    @Inject
    private RegionService regionService;
    
    @Inject 
    private MemberService memberService;
    
    @RequestMapping(value="/register", method=RequestMethod.GET)
    public String prepare(Model model) {
        return "chooseRegType";
    }
    
    @RequestMapping(value="/register/person", method=RequestMethod.GET)
    public String preRegisterPerson(WebRequest request, HttpServletResponse response, Model model) throws IOException {
        PersonMember pm = new PersonMember();
        model.addAttribute("personMember", pm);
        return "registerPerson";
    }
    
    @RequestMapping(value="/register/person", method=RequestMethod.POST)
    public String registerPerson(@Valid PersonMember personMember, 
    		BindingResult result, 
    		Model model,
    		HttpServletRequest request,
    		RedirectAttributes redirectAttrs) {
        //System.out.println(personMember);
        if(personMember.getId()==null&&memberService.getMember(personMember.getUsername())!=null){
        	// a good case
        	result.rejectValue("username", "", "用户名不可用");
        }
        
        if(!WebUtils.checkValidCode(request)){
        	result.rejectValue("validCode", "", "验证码错误");
        }
        
        if(!personMember.getPassword().equals(personMember.getPassword1())){
        	result.rejectValue("password1", "", "两次密码输入不一致");	
        }
        
        if (result.hasErrors()) {
            return "registerPerson";
        }
        
        Region region = regionService.getRegion(personMember.getRegionId());
        personMember.setRegion(region);
        memberService.saveMember(personMember);
        String message = "表单提交成功";
        model.addAttribute("message", message);
        redirectAttrs.addFlashAttribute("message", message);
        return "registerPerson";
    }
    
    //public String registerCompany(@Valid CompanyMember member, BindingResult result, Model model) {
    
    @RequestMapping(value="/register/company", method=RequestMethod.GET)
    public String preRegisterCompany(Model model) {
        CompanyMember cm = new CompanyMember();
        model.addAttribute("companyMember", cm);
        return "registerCompany";
    }
    
    @RequestMapping(value="/register/company", method=RequestMethod.POST)
    public String registerCompany(@Valid CompanyMember companyMember, 
    		BindingResult result, 
    		HttpServletRequest request,
    		Model model, 
    		RedirectAttributes redirectAttrs) {
        System.out.println(companyMember);
        if(companyMember.getId()==null&&memberService.getMember(companyMember.getUsername())!=null){
        	// a good case
        	result.rejectValue("username", "", "用户名不可用");
        }
        
        if(!WebUtils.checkValidCode(request)){
        	result.rejectValue("validCode", "", "验证码错误");
        }
        if(!companyMember.getPassword().equals(companyMember.getPassword1())){
        	result.rejectValue("password1", "", "两次密码输入不一致");	
        }
        if (result.hasErrors()) {
            return "registerCompany";
        }
        Region region = regionService.getRegion(companyMember.getRegionId());
        companyMember.setRegion(region);
        memberService.saveMember(companyMember);
        String message = "表单提交成功";
        model.addAttribute("message", message);
        redirectAttrs.addFlashAttribute("message", message);
        return "registerCompany";
    }
    
    @RequestMapping(value="/admin/member/list", method=RequestMethod.GET)
    public String list(@Valid MemberSearchForm form, WebRequest request, Model model){
    	DetachedCriteria dc = null;
    	if(form.getType().equals("person")){
    		dc = DetachedCriteria.forClass(PersonMember.class);
    	}
    	else{
    		dc = DetachedCriteria.forClass(CompanyMember.class);
    	}
    	if(form.getRegionId()!=null){
    		dc.add(Restrictions.like("regionId", form.getRegionId(), MatchMode.START));
    	}
    	PageSearchResult rs = memberService.search(dc, form.getPage(), form.getPageSize());
    	model.addAttribute("results", rs);
    	return null;
    }
    
    @RequestMapping(value="/checkUserExist", method=RequestMethod.GET)
    public @ResponseBody String checkUserExist(String username){
    	Member m = memberService.getMember(username);
    	if(m==null){
    		return "yes";
    	}
    	return "no";
    }
    

    @RequestMapping(value="/login", method=RequestMethod.GET)
    public String login(){
    	return "member/login";
    }
    @RequestMapping(value="/login", method=RequestMethod.POST)
    public String login(Member member, HttpServletResponse response, Model model, HttpSession session) throws IOException{
    	Member m1 = memberService.checkUser(member);
    	if(m1==null){
    		model.addAttribute("message", "用户名或密码不正确");
    		return "member/login";
    	}
    	m1.setRegionId(m1.getRegion().getId());
    	session.setAttribute("member", m1);
    	//response.sendRedirect("search");
    	return "redirect:/search";
    }
    
    @RequestMapping(value="logout")
    public String logout(HttpSession session) throws IOException{
    	session.removeAttribute("member");
    	//response.sendRedirect("search");
    	return "redirect:/search";
    }
    
    @RequestMapping(value="/member/memberCenter")
    public String memberCenter(HttpSession session) throws IOException{
    	//session.removeAttribute("member");
    	//response.sendRedirect("search");
    	return null;
    }
    
    @RequestMapping(value="/member/editMember", method=RequestMethod.GET)
    public String preEdit(HttpSession session, Model model) throws IOException {
        Member m = (Member)session.getAttribute("member");
        
        if(m instanceof PersonMember){
        	model.addAttribute("personMember", m);
        	return "member/editPersonMember";
        }
        else{
        	model.addAttribute("companyMember", m);
        	return "member/editCompanyMember";
        }
    }
    
    @RequestMapping(value="/member/editPersonMember", method=RequestMethod.POST)
    public String editPersonMember(@Valid PersonMember personMember, 
    		BindingResult result, 
    		Model model, 
    		HttpServletRequest request,
    		RedirectAttributes redirectAttrs) throws IOException {
    	if (result.hasErrors()) {
            return "member/editPersonMember";
        }
        if(personMember.getId()==null&&memberService.getMember(personMember.getUsername())!=null){
        	// a good case
        	result.rejectValue("username", "", "用户名不可用");
        	return "member/editPersonMember";
        }
        if(!WebUtils.checkValidCode(request)){
        	result.rejectValue("validCode", "", "验证码错误");
        	return "member/editPersonMember";
        }
        Region region = regionService.getRegion(personMember.getRegionId());
        personMember.setRegion(region);
        memberService.saveMember(personMember);
        String message = "表单提交成功";
        model.addAttribute("message", message);
        redirectAttrs.addFlashAttribute("message", message);
        return "member/editPersonMember";
    }
    
    @RequestMapping(value="/member/editCompanyMember", method=RequestMethod.POST)
    public String editCompanyMember(@Valid CompanyMember companyMember, 
    		BindingResult result, 
    		HttpServletRequest request,
    		Model model, 
    		RedirectAttributes redirectAttrs) {
        System.out.println(companyMember);
        if (result.hasErrors()) {
            return "/member/editCompanyMember";
        }
        if(companyMember.getId()==null&&memberService.getMember(companyMember.getUsername())!=null){
        	// a good case
        	result.rejectValue("username", "", "用户名不可用");
        	return "/member/editCompanyMember";
        }
        if(!WebUtils.checkValidCode(request)){
        	result.rejectValue("validCode", "", "验证码错误");
        	return "/member/editCompanyMember";
        }
        Region region = regionService.getRegion(companyMember.getRegionId());
        companyMember.setRegion(region);
        memberService.saveMember(companyMember);
        String message = "表单提交成功";
        model.addAttribute("message", message);
        redirectAttrs.addFlashAttribute("message", message);
        return "member/editCompanyMember";
    }

}
